<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>乘客信息管理</title>
    <script src="resources/js/jquery-3.7.1.min.js"></script>
    <style>

        .main {
            max-width: 1000px;
            margin: 50px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .search-bar {
            display: flex;
            margin-bottom: 20px;
        }
        .search-bar input {
			width: 200px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            font-size: 14px;
        }
        .search-bar button {
            background-color: #ffffff;
            color: black;
			border: 1px solid #dedede;
            padding: 8px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 10px;
        }
        .search-bar button:hover {
            background-color: #40a9ff;
        }
        .table-container {
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table th, table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }
        table th {
            background-color: #fafafa;
            font-weight: bold;
            color: #333;
        }
        table td {
            color: #666;
        }
        .actions {
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .actions button {
            background-color: #1890ff;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .actions button:hover {
            background-color: #40a9ff;
        }
        .table-actions button {
            background-color: transparent;
            color: #1890ff;
            border: 1px solid #1890ff;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 5px;
        }
        .table-actions button:hover {
            background-color: #1890ff;
            color: white;
        }
        .checkbox {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }


        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            border-radius: 5px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }

        .form-group button {
            background-color: #1890ff;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .form-group button:hover {
            background-color: #40a9ff;
        }
    </style>
</head>
<body>

<div class="main">
    <!-- 搜索栏 -->
    <div class="search-bar">
        <input type="text" placeholder="请输入乘客姓名" >
        <button onclick="searchByName()">查询</button>
        <button onclick="newTable()">刷新</button>
    </div>

    <!-- 操作按钮 -->
    <div class="actions">
        <button onclick="openAddFriendModal()">添加</button>
        <button onclick="deleteSelectedRows()">批量删除</button>
    </div>

    <!-- 表格 -->
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th><input type="checkbox" id="selectAll" class="checkbox" onclick="SelectAll()"></th>
                    <th>序号</th>
                    <th>姓名</th>
                    <th>证件类型</th>
                    <th>证件号码</th>
                    <th>手机 / 电话</th>
                    <th>核验状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tableBody">
                    <td><input type="checkbox" class="checkbox row-checkbox"></td>

            </tbody>
        </table>
    </div>
    <!-- 新增亲友弹窗表单 -->
    <div id="addFriendModal" class="modal">
        <div class="modal-content">
            <h3>新增亲友</h3>
            <form id="addFriendForm">
                <div class="form-group">
                    <label for="friendName">姓名：</label>
                    <input type="text" id="friendName" name="friendName" required>
                </div>
                <div class="form-group">
                    <label for="papersType">证件类型：</label>
                    <select id="papersType" name="papersType" required>
                        <option value="居民身份证">居民身份证</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="friendPapers">证件号码：</label>
                    <input type="text" id="friendPapers" name="friendPapers" required>
                </div>
                <div class="form-group">
                    <label for="friendPhone">手机 / 电话：</label>
                    <input type="text" id="friendPhone" name="friendPhone" required>
                </div>
                <div class="form-group">
                    <button type="button" onclick="saveFriend()">提交</button>
                    <button type="button" onclick="closeAddFriendModal()">取消</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 修改亲友信息的弹窗 -->
    <div id="editFriendModal" class="modal">
        <div class="modal-content">
            <h3>编辑亲友信息</h3>
            <form id="editFriendForm">
                <div class="form-group">
                    <label for="editFriendName">姓名：</label>
                    <input type="text" id="editFriendName" name="editFriendName" readonly style="background-color:antiquewhite">
                </div>
                <div class="form-group">
                    <label for="editPapersType">证件类型：</label>
                    <input type="text" id="editPapersType" name="editPapersType" readonly style="background-color:antiquewhite">
                </div>
                <div class="form-group">
                    <label for="editFriendPapers">证件号码：</label>
                    <input type="text" id="editFriendPapers" name="editFriendPapers" readonly style="background-color:antiquewhite">
                </div>
                <div class="form-group">
                    <label for="editFriendPhone">手机 / 电话：</label>
                    <input type="text" id="editFriendPhone" name="editFriendPhone" required>
                </div>
                <div class="form-group">
                    <button type="button" onclick="updateFriend()">提交</button>
                    <button type="button" onclick="closeEditFriendModal()">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // 打开新增亲友弹窗
    function openAddFriendModal() {
        document.getElementById('addFriendModal').style.display = 'block';
    }

    // 关闭新增亲友弹窗
    function closeAddFriendModal() {
        document.getElementById('addFriendModal').style.display = 'none';
    }

    // 关闭编辑亲友信息弹窗
    function closeEditFriendModal() {
        document.getElementById('editFriendModal').style.display = 'none';
    }

    // 页面加载时获取乘车人列表
    window.onload = function() {
        let user = sessionStorage.getItem('user');
        const parsedUser = JSON.parse(user);
        const userId =parsedUser.userId
        if (userId) {
            FriendList(userId);
        } else {
            alert('用户未登录');
        }
    };

    // 获取乘车人列表
    function FriendList(userId) {
        $.ajax({
            url: 'friends/select',
            type: 'get',
            data:{
                userId:userId
            },
            dataType:'JSON',
            success: function(response) {

                // 处理服务器返回的数据
                if (response.code == 200) {
                    renderTable(response.data.data);
                }else {
                    alert('获取乘车人列表失败');
                }
            }
        })

    }

    // 渲染表格
    function renderTable(friendList) {
        var $tableBody = $("#tableBody");
        $tableBody.empty(); // 清空表格内容
        var tr = "";

        // 遍历乘车人列表，动态生成表格行
        for (let i = 0; i < friendList.length; i++) {
            let friend = friendList[i];
            tr += `
                <tr>
                    <td><input type="checkbox" class="checkbox row-checkbox"></td>
                    <td>${i+1}</td>
                    <td>${friend.friendName}</td>
                    <td>${friend.papersType}</td>
                    <td>${friend.friendPapers}</td>
                    <td>${friend.friendPhone}</td>
                    <td>${friend.friendNote}</td>
                    <td className="table-actions">
                        <button onClick="editFriend('${friend.friendId}')">编辑</button>
                        <button onClick="deleteFriend('${friend.friendId}')">删除</button>
                    </td>
                </tr>
            `
        }
        $tableBody.append(tr); // 将行添加到表格中
    }

    // 刷新表格
    function newTable() {
        let user = sessionStorage.getItem('user');
        const parsedUser = JSON.parse(user);
        const userId = parsedUser.userId;
        if (userId) {
            // 清空搜索输入框
            document.querySelector('.search-bar input').value = '';
            FriendList(userId); // 重新加载数据
        } else {
            alert('用户未登录');
        }
    }

    // 根据姓名查询
    function searchByName() {
        const friendName = document.querySelector('.search-bar input').value;
        if (!friendName) {
            alert('请输入乘客姓名');
            return;
        }

        $.ajax({
            url: 'friends/selectByName',
            type: 'get',
            data: {
                friendName: friendName // 将乘客姓名作为查询条件传递给后端
            },
            dataType: 'JSON',
            success: function(response) {
                console.log(response.data.data)
                // 处理服务器返回的数据
                if (response.code == 200) {
                    renderTable(response.data.data); // 渲染查询结果
                } else {
                    alert('查询失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX 请求失败:', status, error);
                alert('查询失败，请稍后重试');
            }
        });
    }

    // 全选/取消全选
    function SelectAll() {
        const selectAll = document.getElementById('selectAll');
        const checkboxes = document.querySelectorAll('.row-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectAll.checked;
        });
    }

    // 批量删除
    function deleteSelectedRows() {
        const checkboxes = document.querySelectorAll('.row-checkbox:checked');
        if (checkboxes.length === 0) {
            alert('请选择要删除的行！');
            return;
        }

        if (confirm('确定要删除选中的行吗？')) {
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                const friendId = row.querySelector('td:nth-child(2)').textContent;

                $.ajax({
                    url: 'friends/deletes', // 后端批量删除接口
                    type: 'delete',
                    contentType: 'application/json',
                    data: JSON.stringify(friendId),
                    dataType:'JSON',
                    success: function(response) {
                        if (response.code === 200) {
                            alert('删除成功！');
                            newTable(); // 刷新表格
                        } else {
                            alert('删除失败');
                        }
                    },
                    error: function() {
                        alert('请求失败，请稍后重试');
                    }
                });

            });

        }
    }

    // 删除单个乘车人
    function deleteFriend(friendId) {
        if (confirm('确定要删除该乘车人吗？')) {
            $.ajax({
                url: `friends/delete?friendId=${friendId}`,
                type: 'delete',
                data: {
                    friendId: friendId,
                },
                dataType:'JSON',
                success: function(response) {
                    if (response.code === 200) {
                        alert('删除成功！');
                        newTable();
                    } else {
                        alert('删除失败');
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        }
    }
    //新增
    function saveFriend() {
        const friendName = document.getElementById('friendName').value;
        const papersType = document.getElementById('papersType').value;
        const friendPapers = document.getElementById('friendPapers').value;
        const friendPhone = document.getElementById('friendPhone').value;


        // 输入是否为空
        if (!friendName || !papersType || !friendPapers || !friendPhone ) {
            alert('请填写完整信息');
            return;
        }

        // 身份证号码格式
        const idCardRegex = /^\d{15}(\d{2}[0-9xX])?$/; // 身份证号码正则
        if (!idCardRegex.test(friendPapers)) {
            alert('身份证号码格式不正确');
            return;
        }
        
        // 手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号正则
        if (!phoneRegex.test(friendPhone)) {
            alert('手机号格式不正确');
            return;
        }

        // 获取用户ID
        let user = sessionStorage.getItem('user');
        const parsedUser = JSON.parse(user);
        const userId = parsedUser.userId;

        if (!userId) {
            alert('用户未登录');
            return;
        }

        // 发起新增亲友的请求
        $.ajax({
            url: 'friends/add',
            type: 'post',
            data: {
                userId: userId,
                friendName: friendName,
                papersType: papersType,
                friendPapers: friendPapers,
                friendPhone: friendPhone,

            },
            dataType: 'JSON',
            success: function(response) {
                if (response.code === 200) {
                    alert('新增成功！');
                    closeAddFriendModal(); // 关闭弹窗
                    newTable(); // 刷新表格
                } else {
                    alert('新增失败');
                }
            },
            error: function() {
                alert('请求失败，请稍后重试');
            }
        });
    }
    // 打开编辑亲友信息弹窗
    function editFriend(friendId) {
        // 显示弹窗
        document.getElementById('editFriendModal').style.display = 'block';

        // 获取用户ID
        let user = sessionStorage.getItem('user');
        const parsedUser = JSON.parse(user);
        const userId = parsedUser.userId;

        if (!userId) {
            alert('用户未登录');
            return;
        }

        // 调用后端接口获取亲友信息
        $.ajax({
            url: `friends/selectById`,
            type: 'get',
            data: {
                friendId:friendId,
            },
            dataType: 'JSON',
            success: function(response) {
                if (response.code === 200) {
                    const friend = response.data.data;

                    // 回显亲友信息到表单
                    document.getElementById('editFriendName').value = friend.friendName;
                    document.getElementById('editPapersType').value = friend.papersType;
                    document.getElementById('editFriendPapers').value = friend.friendPapers;
                    document.getElementById('editFriendPhone').value = friend.friendPhone;

                    // 将 friendId 存储到 editFriendPhone 的 dataset 中
                    document.getElementById('editFriendPhone').dataset.friendId = friendId;
                } else {
                    alert('获取亲友信息失败');
                }
            },
            error: function() {
                alert('请求失败，请稍后重试');
            }
        });
    }
    //修改亲友信息
    function updateFriend() {
        // 从 editFriendPhone 的 dataset 中获取 friendId
        const friendId = document.getElementById('editFriendPhone').dataset.friendId;
        const friendPhone = document.getElementById('editFriendPhone').value;

        // 校验手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号正则
        if (!phoneRegex.test(friendPhone)) {
            alert('手机号格式不正确');
            return;
        }

        $.ajax({
            url: 'friends/update',
            type: 'put',
            contentType: 'application/json',
            data: JSON.stringify({
                friendId: friendId,
                friendPhone: friendPhone
            }),
            dataType: 'JSON',
            success: function(response) {
                if (response.code === 200) {
                    alert('修改成功！');
                    closeEditFriendModal(); // 关闭弹窗
                    newTable(); // 刷新表格
                } else {
                    alert('修改失败');
                }
            },
            error: function() {
                alert('请求失败，请稍后重试');
            }
        });
    }
</script>
</body>
</html>